package com.teradata.dashboard.ui.activity;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.teradata.dashboard.DashboardApplication;
import com.teradata.dashboard.R;
import com.teradata.dashboard.constant.DashboardConstant;
import com.teradata.dashboard.dialog.CustomDialog;
import com.teradata.dashboard.utils.DialogUtil;
import com.teradata.dashboard.utils.HttpUtil;




public class LoginActivity extends Activity implements OnClickListener  {
	SharedPreferences preferences;
    SharedPreferences.Editor editor;
    String uName = "";
    String pWord = "";
    JSONObject jsonObj;
    JSONObject data;
    EditText userName;
    EditText password;
    
    CustomDialog dialog1;
 //   ProgressDialog pd = null;
    
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.login);  
        Button btn_login = (Button) findViewById(R.id.btn_login);
        
        userName = (EditText) findViewById(R.id.et_account);
        password = (EditText) findViewById(R.id.et_password);
        
        //初始化sharePreferences
        preferences = this.getSharedPreferences("userInof", MODE_WORLD_READABLE);
        editor = preferences.edit();
       
        TextView text_forget = (TextView) findViewById(R.id.text_forget);
        TextView btn_resign = (TextView) findViewById(R.id.btn_resign);
        

        uName = preferences.getString("USER_NAME", "");
        pWord = preferences.getString("PASS_WORD", "");
        
        if( !uName.equals("") && !pWord.equals(""))
        {
        	
        	userName.setText(uName);
        	password.setText(pWord);
        	
        	
        	////显示登陆对话框
        	dialog1 = new CustomDialog(this, 180, 180, R.layout.loading_dialog, R.style.Theme_dialog);
            dialog1.show();
            dialog1.setCanceledOnTouchOutside(false);
           
            Runnable run = new Runnable(){
            	public void run()
            	{
            		try {
    					Thread.sleep(1000 * 10);
    					dialog1.dismiss();
    				} catch (InterruptedException e) {
    					// TODO 自动生成的 catch 块
    					e.printStackTrace();
    				}
            	}
            };
            Thread clock = new Thread(run);
            clock.start();
           
            try{
        		login(uName, pWord);
        		//jsonObj = query(uName, pWord);
        		
        	}
        	catch (Exception e)
    		{
    			e.printStackTrace();
    		}
        	
        }
        
        
        btn_login.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		//show.setText("");
        		
        		//pd = ProgressDialog.show(LoginActivity.this, "MDashboard", "登陆中...");
        		dialog1 = new CustomDialog(LoginActivity.this, 180, 180, R.layout.loading_dialog, R.style.Theme_dialog);
                dialog1.show();
                dialog1.setCanceledOnTouchOutside(false);
               
                Runnable run = new Runnable(){
                	public void run()
                	{
                		try {
        					Thread.sleep(1000 * 10);
        					dialog1.dismiss();
        				} catch (InterruptedException e) {
        					// TODO 自动生成的 catch 块
        					e.printStackTrace();
        				}
                	}
                };
                Thread clock = new Thread(run);
                clock.start();
        		
        		
                //调用service层函数，验证并返回用户详细信息。
                
        		try
        		{
        			login(userName.getText().toString(), password.getText().toString());
        			
        			
        		}
        		catch (Exception e)
        		{
        			e.printStackTrace();
        		}
        	}
        });
        
        btn_resign.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		Bundle data = new Bundle();
            	data.putSerializable("option", "resign");
            	
        		Intent intent = new Intent(LoginActivity.this, ResignActivity.class);
            	startActivity(intent);
        	}
        });
        
        text_forget.setOnClickListener(new OnClickListener(){
        	public void onClick(View v)
        	{
        		Bundle data = new Bundle();
            	data.putSerializable("option", "forget");
        		Intent intent = new Intent(LoginActivity.this, ResignActivity.class);
            	startActivity(intent);
            	
        	}
        });
        
    }

	private void login(final String username, final String password) throws JSONException {
		
		// 定义发送请求的URL
		String url = "tpifauth/authUser.action";
		// 发送请求
		RequestParams requestParams=new RequestParams();
		requestParams.add("userId", username);
		requestParams.add("password", password);
		HttpUtil.post(url, requestParams, new JsonHttpResponseHandler(){
			 @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
				//pd.dismiss();
				 dialog1.dismiss();
				try {
					data=response.getJSONObject("data");
				
					System.out.println(data.getString("authResultType"));
			    	if( "01".equals(data.getString("authResultType")))
			    	{
			    		//写入sharedPreferences
			        	editor.putString("USER_NAME", username);
			        	editor.putString("PASS_WORD", password);
			        	editor.commit();
			        	
			        	DashboardApplication.app.setMyCookie(data.getString(DashboardConstant.AUTH_KEY_COOKIE_NAME));
			        	HttpUtil.initCookieManager();
			            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
			            startActivity(intent);
			    	}else if("02".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this,"用户名或密码有误", false);
	     				
	                 }
	     			else if("03".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, "新建用户，未授予权限", false);
	     			}
	     			else if("04".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, "用户被禁用，提示不予登录", false);
	     			}
	     			else if("05".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, "密码连续输错，用户被停用，提示不予登录", false);
	     			}
	     			else if("06".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, "首次登录用户，密码为初始密码，提示并转至密码修改界面", false);
	     			}
	     			else if("07".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, "密码即将到期用户，提示及时修改密码", false);
	     			}
	     			else if("08".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, "用户数超过限制，提示不予登录", false);
	     			}
	     			else if("09".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, "用户登录IP和等级IP不一致，提示不予登录", false);
	     			}
	     			else if("10".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, "非工作时间，不予登录", false);
	     			}
	     			else if("11".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, "系统维护中，不予登录", false);
	     			}
	     			else if("99".equals(data.getString("authResultType")))
	     			{
	     				DialogUtil.showDialog(LoginActivity.this, " 未知错误", false);
	     			}
		    	} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
			 @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                // Pull out the first event on the public timeline
                JSONObject firstEvent;
                String tweetText="";
				try {
					firstEvent = (JSONObject)response.get(0);
					tweetText = firstEvent.getString("text");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                

                // Do something with the response
                System.out.println(tweetText);
            }
		});
	}

	@Override
	public void onClick(View arg0) {
		// TODO 自动生成的方法存根
		
	}  
	
	// 定义发送请求的方法
		private JSONObject query(String username, String password)
			throws Exception
		{
			//使用Map封装请求参数
			Map<String, String> map = new HashMap<String, String>();
			map.put("userId", username);
			map.put("password", password);
			// 定义发送请求的URL
			String url = HttpUtil.BASE_URL + "tpifauth/authUser.action";
			// 发送请求
			return new JSONObject(HttpUtil.postRequest(url, map));
		}
		
		// 对用户输入的用户名、密码进行校验
		private boolean validate()
		{
			EditText userName = (EditText) findViewById(R.id.et_account);
            EditText password = (EditText) findViewById(R.id.et_password);
			String username = userName.getText().toString().trim();
			if (username.equals(""))
			{
				DialogUtil.showDialog(this, "用户账户是必填项！", false);
				return false;
			}
			String pwd = password.getText().toString().trim();
			if (pwd.equals(""))
			{
				DialogUtil.showDialog(this, "用户口令是必填项！", false);
				return false;
			}
			return true;
		}

}
